//
//  CRPicNewsViewController.m
//  NewAge
//
//  Created by dllo on 15/11/30.
//  Copyright © 2015年 ColorRevolution. All rights reserved.
//

#import "CRPicNewsViewController.h"
#import "CRPicNewsModel.h"
#import "CRPicNewsCollectionViewCell.h"

@interface CRPicNewsViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

{
    UIView *_headBgView;
    UIButton *_backButton;
}

@property (nonatomic, strong) NSMutableArray *picArr;
@property (nonatomic, strong) NSString *titleStr;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *pageLabel;
@property (nonatomic, strong) UILabel *contentLabel;

@property (nonatomic, strong) UIButton *downLoadButton;

@end

@implementation CRPicNewsViewController

#pragma mark - init

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.picArr = [NSMutableArray array];
    }
    return self;
}



#pragma mark - createData

- (void)createData {
    [AfNetWorkingManager getInfoWithUrl:self.url block:^(NSDictionary *resultDic, NSError *error) {
        if (resultDic) {
            self.picArr = [CRPicNewsModel baseModelByArr:resultDic[@"photos"]];
            self.titleStr = resultDic[@"setname"];
            
            [self createViews];
            
            [self.collectionView reloadData];
        }
        else {
            NSLog(@"ERROR ====%@", error);
        }
    }];
}



#pragma mark - createViews

- (void)createCollectionView {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    flowLayout.itemSize = CGSizeMake(WIDTH, HEIGHT);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) collectionViewLayout:flowLayout];
    [self.view addSubview:self.collectionView];
    _collectionView.pagingEnabled = YES;
    [self.view addSubview:_collectionView];
    
    [_collectionView registerClass:[CRPicNewsCollectionViewCell class] forCellWithReuseIdentifier:@"pnReuse"];
}

- (void)createViews {
    
    _headBgView = [[UIView alloc] init];
    [self.view addSubview:_headBgView];
    _backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [_backButton setBackgroundImage:[UIImage imageNamed:@"iconfont-fanhui.png"] forState:UIControlStateNormal];
    [_backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [_headBgView addSubview:_backButton];
    
    self.titleLabel = [[UILabel alloc] init];
    _titleLabel.textColor = [UIColor whiteColor];
    _titleLabel.text = self.titleStr;
    [self.view addSubview:_titleLabel];
    
    self.pageLabel = [[UILabel alloc] init];
    _pageLabel.textColor = [UIColor whiteColor];
    _pageLabel.font = [UIFont systemFontOfSize:13];
    NSString *page = [NSString stringWithFormat:@"%g / %ld", self.collectionView.contentOffset.x / WIDTH + 1, self.picArr.count];
    
    NSString *pageNum = [NSString stringWithFormat:@"%g", self.collectionView.contentOffset.x / WIDTH + 1];
    
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:page];
    [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17] range:NSMakeRange(0, pageNum.length)];
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, pageNum.length)];
    _pageLabel.attributedText = attributedString;
    _pageLabel.textAlignment = NSTextAlignmentRight;
    [self.view addSubview:_pageLabel];
    
    self.scrollView = [[UIScrollView alloc] init];
    [self.view addSubview:_scrollView];
    
    self.contentLabel = [[UILabel alloc] init];
    _contentLabel.textColor = [UIColor whiteColor];
    _contentLabel.font = [UIFont systemFontOfSize:14];
    _contentLabel.numberOfLines = 0;
    [self.scrollView addSubview:_contentLabel];
    
    _contentLabel.text = [self.picArr[0] note];
    
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:14], NSFontAttributeName, nil];
    
    CGRect rect = [[self.picArr[0] note] boundingRectWithSize:CGSizeMake(WIDTH - 30 * WIDTH / 375.0, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    
    _scrollView.contentSize = CGSizeMake(0, rect.size.height);
    _contentLabel.frame = CGRectMake(0, 0, WIDTH - 30 * WIDTH / 375.0, rect.size.height);
    
    if (rect.size.height > 80 * HEIGHT / 667.0) {
        _scrollView.frame = CGRectMake(15 * WIDTH / 375.0, HEIGHT - 120 * HEIGHT / 667.0, WIDTH - 20 * WIDTH / 375.0, 80 * HEIGHT / 667.0);
    }
    
    else {
        _scrollView.frame = CGRectMake(15 * WIDTH / 375.0, HEIGHT - rect.size.height - 40 * HEIGHT / 667.0, WIDTH - 20 * WIDTH / 375.0, 80 * rect.size.height);
    }
    [self setLayout];
}

- (void)setLayout {
    
    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        Bottom(_scrollView.mas_top, 0);
        Left(self.view.mas_left, 15 * WIDTH / 375.0);
        HequalNum(25 * HEIGHT / 667.0);
    }];
    
    [_pageLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        Bottom(_scrollView.mas_top, 0);
        Right(self.view.mas_right, -15 * WIDTH / 375.0);
        HequalNum(25 * HEIGHT / 667.0);
        WequalNum(70 * WIDTH / 375.0);
    }];
    
    [_headBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        Top(self.view, 0);
        Left(self.view, 0);
        Right(self.view, 0);
        HequalNum(64 * HEIGHT / 667.0);
    }];
    
    [_backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        Top(_headBgView.mas_top, 34 * HEIGHT / 667.0);
        Bottom(_headBgView.mas_bottom, -10 * HEIGHT / 667.0);
        Left(_headBgView.mas_left, 10 * HEIGHT / 667.0);
        WequalNum(20 * HEIGHT / 667.0);
        HequalNum(20 * HEIGHT / 667.0);
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.hidden = YES;
    self.navigationController.navigationBar.translucent = NO;
    
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
}

- (void)viewWillDisappear:(BOOL)animated {
//    _collectionView.dataSource = nil;
//    _collectionView.delegate = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self createCollectionView];
    [self createData];
    

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



#pragma mark - collectionViewDateSoure & Delegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.picArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CRPicNewsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"pnReuse" forIndexPath:indexPath];
    [cell.picView sd_setImageWithURL:[NSURL URLWithString:[self.picArr[indexPath.row] imgurl]] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        [cell.picView mas_makeConstraints:^(MASConstraintMaker *make) {
            Left(cell.mas_left, 0);
            Right(cell.mas_right, 0);
            CenterY(cell.mas_centerY);
            HequalNum(image.size.height * WIDTH / image.size.width);
        }];
    
//        cell.contentLabel.text = [self.picArr[indexPath.row] note];
        
//        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:14], NSFontAttributeName, nil];
        
//        CGRect rect = [[self.picArr[indexPath.row] note] boundingRectWithSize:CGSizeMake(WIDTH - 20 * WIDTH / 375.0, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
//        cell.scrollView.contentSize = CGSizeMake(0, rect.size.height);
        
//        cell.contentLabel.backgroundColor = [UIColor blueColor];
//        if (rect.size.height > 50 * HEIGHT / 667.0) {
//            [cell.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
//                Left(cell.mas_left, 10 * WIDTH / 375.0);
//                Right(cell.mas_right, -10 * WIDTH / 375.0);
//                Bottom(cell.mas_bottom, -50 * HEIGHT / 667.0);
//                HequalNum(50 * HEIGHT / 667.0);
//            }];
//        }
//        else {
//            [cell.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
//                Left(cell.mas_left, 10 * WIDTH / 375.0);
//                Right(cell.mas_right, -10 * WIDTH / 375.0);
//                Bottom(cell.mas_bottom, -50 * HEIGHT / 667.0);
//                HequalNum(rect.size.height);
//            }];
//        }
//        
//        [cell.contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//            Top(cell.scrollView.mas_top, 0);
//            Left(cell.scrollView.mas_left, 0);
//            Right(cell.scrollView.mas_right, 0);
//            WequalNum(WIDTH - 20 * WIDTH / 375.0);
//            HequalNum(rect.size.height);
//        }];
    }];
    
    // 添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [cell addGestureRecognizer:tap];
    
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(showDonwloadMenuAction:)];
    [cell addGestureRecognizer:longPress];
    [tap requireGestureRecognizerToFail:longPress];
    
    return cell;
}



#pragma mark - ScrollViewDelegate

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    if (scrollView == self.collectionView) {
        NSInteger page = self.collectionView.contentOffset.x / WIDTH;
        CRPicNewsModel *picNews = self.picArr[page];
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:14], NSFontAttributeName, nil];
        CGRect rect = [picNews.note boundingRectWithSize:CGSizeMake(WIDTH - 30 * WIDTH / 375.0, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        
        _scrollView.contentSize = CGSizeMake(0, rect.size.height);
        _contentLabel.frame = CGRectMake(0, 0, WIDTH - 30 * WIDTH / 375.0, rect.size.height);
        
        if (rect.size.height > 80 * HEIGHT / 667.0) {
            _scrollView.frame = CGRectMake(15 * WIDTH / 375.0, HEIGHT - 120 * HEIGHT / 667.0, WIDTH - 20 * WIDTH / 375.0, 80 * HEIGHT / 667.0);
        }
        
        else {
            _scrollView.frame = CGRectMake(15 * WIDTH / 375.0, HEIGHT - rect.size.height - 40 * HEIGHT / 667.0, WIDTH - 20 * WIDTH / 375.0, 80 * rect.size.height);
        }
        _contentLabel.text = picNews.note;
        NSString *pageStr = [NSString stringWithFormat:@"%g / %ld", self.collectionView.contentOffset.x / WIDTH + 1, self.picArr.count];
        
        NSString *pageNum = [NSString stringWithFormat:@"%g", self.collectionView.contentOffset.x / WIDTH + 1];
        
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:pageStr];
        [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17] range:NSMakeRange(0, pageNum.length)];
        [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, pageNum.length)];
        _pageLabel.attributedText = attributedString;
        
    }
}

#pragma mark - ButtonAction

- (void)backAction {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)tapAction:(UITapGestureRecognizer *)tap {
    _headBgView.hidden = !_headBgView.hidden;
    self.titleLabel.hidden = !_titleLabel.hidden;
    self.scrollView.hidden = !_scrollView.hidden;
    self.pageLabel.hidden = !_pageLabel.hidden;
    
    _downLoadButton.hidden = YES;
}

- (void)showDonwloadMenuAction:(UILongPressGestureRecognizer *)longPress {
    if (!_downLoadButton) {
        self.downLoadButton = [UIButton buttonWithType:UIButtonTypeSystem];
        _downLoadButton.backgroundColor = [UIColor lightGrayColor];
        [_downLoadButton setTitle:@"下载图片" forState:UIControlStateNormal];
        _downLoadButton.titleLabel.font = [UIFont systemFontOfSize:12];
        _downLoadButton.tintColor = [UIColor whiteColor];
        [_downLoadButton addTarget:self action:@selector(downloadAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:self.downLoadButton];
    }
    
    _downLoadButton.hidden = NO;
    CGPoint point = [longPress locationInView:longPress.view];
    _downLoadButton.frame = CGRectMake(point.x, point.y + 10, 50, 20);
}

- (void)downloadAction:(UIButton *)button {
    NSInteger page = self.collectionView.contentOffset.x / WIDTH;
    CRPicNewsCollectionViewCell *cell = (CRPicNewsCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:page inSection:0]];
    UIImage *image = cell.picView.image;
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    
}


- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    
    
    
    if (error == NULL) {
        [MBProgressHUDManager showTextHUDtoView:self.view string:@"图片保存成功" showPlace:Center height:15];
    }
    else {
        [MBProgressHUDManager showDetailsTextHUDtoView:self.view string:[NSString stringWithFormat:@"图片保存失败! \n%@", error] showPlace:Center];
    }
    _downLoadButton.hidden = YES;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
